<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <!-- <el-form-item label="线边库类型">
          <el-select
            v-model="searchParam.produceStorageType"
            placeholder="请选择线边库类型"
            clearable
          >
            <el-option
              v-for="item in useDictionary('ProduceStorageType')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantId"
            placeholder="请输入工厂"
            clearable
            @keyup.enter="search"
            @change="closeDialog(searchParam.plantId)"
            filterable
          >
            <el-option
              v-for="item in plantList"
              :key="item.id"
              :label="item.organizationCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车间">
          <el-select
            v-model="searchParam.workCenterId"
            placeholder="请选择车间"
            :disabled="searchParam.plantId === ''"
            clearable
            @keyup.enter="search"
            filterable
          >
            <el-option
              v-for="item in workshopList"
              :key="item.id"
              :label="`${item.shopFloorCode}-${item.shopFloorName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工厂编号">
          <el-input
            v-model="searchParam.plantCode"
            placeholder="请输入工厂编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="车间编号">
          <el-input
            v-model="searchParam.workshopCode"
            placeholder="请输入车间编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="线边库编号">
          <el-input
            v-model="searchParam.produceStorageCode"
            placeholder="请输入线边库编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <!-- <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        > -->
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <template v-for="item in tableColumns" :key="item">
          <TableColumn v-if="item.prop && item.isShow" :column="item">
            <template v-for="slot in Object.keys($slots)" #[slot]="scope">
              <slot :name="slot" v-bind="scope"></slot>
            </template>
          </TableColumn>
        </template>
        <!-- <el-table-column
          label="工厂"
          prop="plantCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="车间"
          prop="workshopCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="线边库编号"
          prop="produceStorageCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="线边库类型"
          prop="produceStorageType"
          min-width="100"
        >
          <template #default="scope">
            {{
              useDictionary("ProduceStorageType", scope.row.produceStorageType)
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="外部编号"
          prop="externalCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="启用状态"
          prop="enabled"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          prop="remarks"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="200"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="更新时间"
          prop="lastUpdateTime"
          min-width="200"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="更新人"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
        /> -->

        <el-table-column fixed="right" label="操作" width="200" align="center">
          <template #default="scope">
            <!-- <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button> -->
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mesproducestorage-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <!-- 列设置 -->
    <ColSetting
      v-model:col-setting="tableColumns"
      v-model:search-setting="searchColumns"
      @search-handle="(e:boolean) => (showSearch = e)"
    />
  </div>
</template>

<script setup lang="tsx">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "MESMESPRODUCESTORAGE",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mesproducestorage/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  plantId: "",
  workshopId: "",
  produceStorageCode: "",
  externalCode: "",
  produceStorageType: "",
  plantCode: "",
  workshopCode: "",
  workshopName: "",
};

const deleteParam = {
  api: "/mes/mesproducestorage/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  getPlantList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mesproducestorage/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
//工厂列表
const plantList = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
  searchParam.value.plantId = plantList.value[0].id;
  closeDialog(searchParam.plantId);
};
function closeDialog(plantId: String) {
  getWorkshopList(plantId);
}
//工作中心
const workshopList = ref([]);
const getWorkshopList = async (plantId: String) => {
  const { data } = await request({
    url: "mdm/mdmshopfloor/getList",
    method: "post",
    data: { plantId: plantId },
  });
  workshopList.value = data;
};
/** 打开线边库（新增表）表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改线边库";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增线边库";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开线边库（新增表）表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "线边库详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/mes/mesproducestorage/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}

const tableColumns = reactive([
  {
    prop: "plantCode",
    label: "工厂",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "workshopCode",
    label: "车间",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "produceStorageCode",
    label: "线边库编号",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "produceStorageType",
    label: "线边库类型",
    minWidth: 100,
    isShow: true,
    align: "left",
    render: (scope: any) =>
      useDictionary("ProduceStorageType", scope.row.produceStorageType),
  },

  {
    prop: "externalCode",
    label: "外部编号",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "enabled",
    label: "启用状态",
    minWidth: 100,
    isShow: true,
    align: "center",
    // render: (scope: any) => (scope.row.enabled === 1 ? "启用" : "停用"),
    render: (scope: any) =>
      scope.row.enabled == "1" ? (
        <el-tag type="success">启用</el-tag>
      ) : scope.row.enabled == "0" ? (
        <el-tag type="info" type="success">
          停用
        </el-tag>
      ) : (
        <div></div>
      ),
  },
  {
    prop: "remarks",
    label: "备注",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "createTime",
    label: "创建时间",
    minWidth: 200,
    isShow: true,
    align: "center",
  },
  {
    prop: "createdUserName",
    label: "创建人",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "lastUpdateTime",
    label: "更新时间",
    minWidth: 200,
    isShow: true,
    align: "center",
  },
  {
    prop: "lastUpdatedUserName",
    label: "更新人",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
]);

//  render: (scope: any) =>
//       scope.row.repairLevel == "1" && scope.row.repairLevel * 1 < 4 ? (
//         <el-tag type="danger">
//           {useDictionary("EamFaultLevel", scope.row.repairLevel)}
//         </el-tag>
//       ) : scope.row.repairStatus * 1 >= 4 ? (
//         <el-tag type="info" type="success">
//           {useDictionary("EamFaultLevel", scope.row.repairLevel)}
//         </el-tag>
//       ) : scope.row.repairLevel !== "1" && scope.row.repairStatus * 1 < 4 ? (
//         <el-tag>{useDictionary("EamFaultLevel", scope.row.repairLevel)}</el-tag>
//       ) : (
//         <div></div>
//       ),
const searchColumns = ref([]);
</script>
